<?php

namespace App\Repositories;

use App\Exceptions\BasicException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redis;
use function Matrix\add;    //引入hash

class NoticeRepository {

    /**
     * 新增
     * @param $param
     * @return bool
     * @throws BasicException
     */
    public function addNotice($param) {
        $addConfig = app('model_notice')->create($param);

        if ($addConfig) return $addConfig;
        throw new BasicException(93045);
    }

    /**
     * 删除
     */
    public function delNotice($idArr = []) {
        $res = app('model_notice')->whereIn("notice_id", $idArr)->update([
            "status" => 3,
            "update_time" => time(),
        ]);

        if ($res) return $res;
        throw new BasicException(93044);
    }

    /**
     * 发布
     */
    public function releaseNotice($idArr = []) {
        $res = app('model_notice')->whereIn("notice_id", $idArr)->where("status","<>",3)->update([
            "status" => 2,
            "update_time" => time(),
        ]);

        if ($res) return $res;
        throw new BasicException(93047);
    }

    /**
     * 修改
     */
    public function saveNotice($where,$param) {
        $saveConfig = app('model_notice')->where($where)->update($param);

        if ($saveConfig) return $saveConfig;
        throw new BasicException(93047);
    }


    /**
     * 管理员后台查询配置数据
     */
    public function getNoticeQueryList(Array $params) {
        $whereArr = [];
        if (!empty($params["type"])) {
            $whereArr[] = ["type", "=", $params["type"]];
        }
        if (!empty($params["status"])) {
            $whereArr[] = ["status", "=", $params["status"]];
        }

        $whereFunc = function ($query) use ($params) {
            if (!empty($params["keyword"])) {
                $query->where('notice_title', 'like', "%" . $params['keyword'] . "%");
            }
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        $result = app('model_notice')->with("admin:admin_id,admin_name")->where($whereArr)->where($whereFunc)->orderBy('notice_id','desc')->paginate($perPage, ['*'], '', $page);

        foreach ($result as $item) {
            $item->add_time = date("Y-m-d H:i:s", $item->add_time);
            $item->update_time = date("Y-m-d H:i:s", $item->update_time);
        }

        return $result;
    }

}